package org.shijiagen.manager.controller;

import lombok.RequiredArgsConstructor;
import org.apache.http.util.Asserts;
import org.shijiagen.manager.param.AdminUserParam;
import org.shijiagen.manager.service.AdminUserService;
import org.shijiagen.utils.R;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Optional;

@RestController
@RequiredArgsConstructor
public class AdminUserController {

    private final AdminUserService adminUserService;

    @PostMapping("user/login")
    public R login(@Validated AdminUserParam adminUserParam, HttpSession session){
        Asserts.check(adminUserParam.getVerCode().equalsIgnoreCase(session.getAttribute("captcha").toString()),"验证码错误");
        Optional.ofNullable(adminUserService.login(adminUserParam)).ifPresentOrElse(user->{
            session.setAttribute("userInfo",user);
        },()-> {
            Asserts.check(false,"账号或密码错误！");
        });
        return R.ok("登陆成功");
    }

    @GetMapping("user/logout")
    public R logout(HttpSession session){
        session.invalidate();
        return R.ok("退出登陆成功");
    }
}
